package tms.business.profile;

import tms.model.profile.UserProfileEntity;
import tms.persistence.profile.ProfileProvider;
import tms.util.constants.UiMessage;
import tms.util.exception.ApplicationRuntimeException;
import tms.util.jabber.JabberManager;
import tms.util.security.AppSecurityManager;

import javax.ejb.EJB;
import javax.ejb.Local;
import javax.ejb.Stateless;
import javax.inject.Inject;
import java.util.List;

@Local
@Stateless
public class ProfileService {
    @EJB
    ProfileProvider profileProvider;
    @Inject
    AppSecurityManager appSecurityManager;
    @Inject
    JabberManager jabberManager;

    public void updateProfile(UserProfileEntity profile) {
        if (profile.getJabberActive()) {
            List<UserProfileEntity> profiles = profileProvider.getAllByJabberId(profile.getJabberId());
            if (!profiles.isEmpty() && !profiles.get(0).getId().equals(profile.getId())) {
                throw new ApplicationRuntimeException(UiMessage.JABBER_ID_ALREADY_EXISTS);
            }
        }
        jabberManager.userProfileChanged(appSecurityManager.getUser().getId(), getProfile(profile.getId()), profile);
        profileProvider.updateProfile(profile);
    }

    public UserProfileEntity getProfile(Integer id) {
        return profileProvider.getProfile(id);
    }

    public List<UserProfileEntity> getAllProfiles() {
        return profileProvider.getAllProfiles();
    }
}
